﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CharmL
{
    public class IndexTable
    {
        /// <summary>
        /// int - int is item - index 
        /// index is the index of the current item in list of concepts 
        /// (list of concetps means all concepts in a lattice)
        /// </summary>
        public Dictionary<int, LatticeNode> Indexs { get; set; }

        #region Constructors
        public IndexTable()
        {
            Indexs = new Dictionary<int, LatticeNode>();
        }
        #endregion

        public void AddIndex(int i, LatticeNode node)
        {
            if (!Indexs.ContainsKey(i))
            {
                Indexs.Add(i, node);
            }
            else
            {
                Indexs[i] = node;
            }
        }

        public void UpdateIndexIfExisted(int i, LatticeNode newNode, LatticeNode oldNode)
        {
            if (Indexs.ContainsKey(i) && Indexs[i] == oldNode)
            {
                Indexs[i] = newNode;
            }            
        }


        public bool ContainsKey(int i)
        {
            return Indexs.ContainsKey(i);
        }

        public LatticeNode GetFirstNode(int value)
        {
            if (Indexs.ContainsKey(value))
            {
                //return Indexs[value];
                LatticeNode temp = Indexs[value];
                if (temp.Parent.Count == 0) {
                    return temp;
                } else {
                    LatticeNode newValue = UpdateIndexInParent(temp, value);
                    Indexs[value] = newValue;
                    return newValue;
                }
            }
            else
            {
                return null;
            }
        }

        private LatticeNode UpdateIndexInParent(LatticeNode curNode, int item) {
            LatticeNode temp = curNode;
            foreach (LatticeNode parent in curNode.Parent) {
                if (parent.Items.Contains(item)) {
                    temp = UpdateIndexInParent(parent, item);
                    break;
                }
            }
            return temp;
        }
        //public int GetFirstNode(int i) {
        //    if (Indexs.ContainsKey(i)) {
        //        return Indexs[i];
        //    } else {
        //        return -1;
        //    }
        //}
    }
}
